package cn.yunhe.view;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * @Author: Meng.Liu1@arvato.com
 * @Date: 2018/12/7 18:00
 * @Description:
 * @version: V1.0
 */
public class HttpUtil {

    /**
     * Get请求
     *
     * @param getUrl 请求地址
     */
    public static String httpURLConectionGET(String getUrl) {
        try {
            URL url = new URL(getUrl);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            // addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}
            InetAddress address = InetAddress.getLocalHost();
            String ip=address.getHostAddress();//获得本机IP
            connection.setRequestProperty("ip", ip);  //请求来源IP
            connection.connect(); // 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) { // 循环读取流
                sb.append(line);
            }
            br.close(); // 关闭流
            connection.disconnect(); // 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "系统异常";
        }
    }

    /**
     * 接口调用  POST
     *
     * @param postUrl 请求地址
     * @param parm 参数拼接 like parm ="username=zhagnsan&password=0000"
     */
    public static String httpURLConnectionPOST(String postUrl, String parm) {
        try {
            URL url = new URL(postUrl);
            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)
            // 此时cnnection只是为一个连接对象,待连接中
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);
            // 设置连接输入流为true
            connection.setDoInput(true);
            // 设置请求方式为post
            connection.setRequestMethod("POST");
            // post请求缓存设为false
            connection.setUseCaches(false);
            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);
            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();//获得本机IP
            connection.setRequestProperty("ip", ip);  //请求来源IP
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();
            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            // 将参数输出到连接
            dataout.write(parm.getBytes());
            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "系统异常";
        }
    }


    //=====================================================




    public static String getRegular(String url){
        // 需要访问的接口路径
        // 配置请求信息（请求时间）
        RequestConfig rc = RequestConfig.custom().setSocketTimeout(5000)
                .setConnectTimeout(5000).build();
        // 获取使用DefaultHttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 返回结果
        String result = null;
        try {
            if (url != null) {
                // 创建HttpGet对象，将URL通过构造方法传入HttpGet对象
                HttpGet httpget = new HttpGet(url);
                // 将配置好请求信息附加到http请求中
                httpget.setConfig(rc);
                // 执行DefaultHttpClient对象的execute方法发送GET请求，通过CloseableHttpResponse接口的实例，可以获取服务器返回的信息
                CloseableHttpResponse response = httpclient.execute(httpget);
                try {
                    // 得到返回对象
                    org.apache.http.HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        // 获取返回结果
                        result = EntityUtils.toString(entity);
                        return result;

                    }
                } finally {
                    // 关闭到客户端的连接
                    response.close();
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭http请求
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    //==============

    /**
     * 发送 post请求
     */
    public static String postText(String URL,String text) {
        String obj=null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        httppost.setHeader("Accept", "application/x-www-form-urlencoded");
        try {
            StringEntity s = new StringEntity(text,Charset.forName("UTF-8"));  //对参数进行编码，防止中文乱码
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                //获取相应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    obj= EntityUtils.toString(entity, "UTF-8");
                }

            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
}
